package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static cn.hutool.http.ContentType.JSON;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
@Resource
private StringRedisTemplate stringRedisTemplate;
@Autowired
private ShopTypeMapper shopTypeMapper;
    @Override
    public List<ShopType> cacheShopList() {
        String key = "shopList";
            //查看redis中有没有这些店铺，如果存在直接返回
      List<String> list= stringRedisTemplate.opsForList().range(key, 0, -1);
      if(list != null && !list.isEmpty()){
          List<ShopType> shopTypeList=new ArrayList<>();
          for (String shopType : list) {
              //将每一个string类型转为json对象返回
              ShopType bean = JSONUtil.toBean(shopType, ShopType.class);
              shopTypeList.add(bean);
          }
          return shopTypeList;
      }
      //如果不存在,查询数据库，先保存到redis中，再返回
        List<ShopType> shopList = shopTypeMapper.getShopList();
        if (shopList != null && !shopList.isEmpty()) {
            // 将每个对象序列化为JSON并存入Redis List
            for (ShopType shopType : shopList) {
                stringRedisTemplate.opsForList().rightPush(key, JSONUtil.toJsonStr(shopType));
            }
            // 设置过期时间，避免缓存永远存在
            stringRedisTemplate.expire(key,RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        }
        return shopList;
    }
}
